import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Block} from '@tarojs/components'
import {AtIcon} from "taro-ui";
import Skeleton from 'taro-skeleton'
import {connect} from 'react-redux'
import {
  CityLocation as CityLocationType,
  IndexGoods, Good
} from '../../utils/server.interface'
import {platform} from '../../utils/platform-settting.service'
import {http} from '../../utils/http'
import {
  CUSTOM_DIY_V2,
  CUSTOM_GOODS,
  IDENTITY_IS_SELLER, RESOURCE_URL,
  SCAN_BIND_SELLER, TARO_ENV,
  UPDATE_USER_SHARE_DATE
} from '../../constants/api'
import Headerbar from '../components/header-bar/header-bar'
import CustomMenu from '../components/main-menu/custom-menu'
import CityLocation from '../../components/city-location/city-location'
import {getHeadTop, gotoPage, vcmonitor} from '../../utils/tools'
import {user} from '../../utils/user.service'
import IndexSaleLimit1 from "../../components/index-sale/index-sale-limit-1";
import IndexSaleLimit2 from "../../components/index-sale/index-sale-limit-2";
import IndexSaleLimit3 from "../../components/index-sale/index-sale-limit-3";
import IndexSaleLimit4 from "../components/index-sale/index-sale-limit-4";
import SmallGoodsBox from "../../components/small-goods-box/small-goods-box";
import BigGoodsBox from "../../components/big-goods-box/big-goods-box";
import GzhAuth from "../../components/gzh-auth/gzh-auth";
import {h5Wx} from "../../utils/h5.service";
import ShangxinToday from "../../pages/index/template/shangxinToday/index";
import IndexSaleCommon from "../../components/index-sale/index-sale-common";
import IndexSaleMost from "../../components/index-sale/index-sale-most";
import SwiperRecommend from '../../components/swiper-recommend/swiper-recommend'
import './index.scss'

type PageStateProps = {
  location: CityLocationType
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  systemInfo: any
  showSubTitle: any
  headTopAll: any
  showSearch: any
  scrollTop: any
  pageBgImage: any
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  pageStyle: any
  pageBgColor: any
  pageData: any
  indexGoods: Good[]
  isUser: boolean
  showLeftIcon: boolean
  showLoading: boolean
  pageshowLoading: boolean
  customUuid: string
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(({location}) => ({
  location
}))

class Index extends Component {

  state: PageState =  {
    systemInfo: {},
    headTopAll: 0,
    scrollTop: 0,
    loadMoreStatus: 'loading',
    pageData: {
      custom_backGround: {
        title: '',
        img: 'https://resource.ivcheng.com/resources/system/img/tourist-line.jpg'
      },
      custom_label: [],
      hot_mudidi: [],
      hot_name: '',
      module: []
    },
    pageStyle: 0,
    pageBgColor: '',
    showSearch: '',
    pageBgImage: '',
    showLoading: true,
    isUser: true,
    showSubTitle: false,
    showLeftIcon: true,
    pageshowLoading: true,
    indexGoods: [],
    customUuid: ''
  }

  async UNSAFE_componentWillMount() {
    const customUuid = Taro.getCurrentInstance().router.params.customUuid || 0
    const pageData = await http.get(CUSTOM_DIY_V2, {customUuid})
    if (!pageData) {
      return false
    }
    const headTop: any = getHeadTop()
    let pageStyle = 0
    let pageBgColor = ''
    let pageBgImage = ''
    let showSubTitle = false
    const customBackGround = pageData.custom_backGround
    if (pageData.custom_backGround) {
      if (pageData.custom_backGround.title) {
        await Taro.setNavigationBarTitle({title: pageData.custom_backGround.title});
      }
      if (pageData.custom_backGround.style) {
        pageStyle = customBackGround.style
        pageBgColor = customBackGround.color
        pageBgImage = customBackGround.image
      }
    }
    pageData.module.map(item => {
      if (item.type === 'goods4') {
        showSubTitle = item.data.some(items => items.sub_title)
      }
    })
    this.setState({
      showSubTitle,
      pageStyle,
      pageBgColor,
      pageBgImage,
      showLeftIcon: process.env.P_ENV !== 'kontai',
      customUuid,
      headTopAll: headTop.statusBar + headTop.top,
      pageData,
      showSearch: http.getSiteHash() !== 'ffd23ded-dc2a-40d0-80a3-7f479313b501',
      showLoading: false
    }, async () => {
      this.setState({ pageshowLoading: false });
      if (pageData.guessLike >= 0 && pageData.data_num == 1) {
        const indexGoods = await this.getIndexGoods(this.page);
        this.setState({ indexGoods });
      }
    })
  }


  async componentDidShow() {
    const pageData = this.state.pageData;
    if (pageData && pageData.custom_backGround && pageData.custom_backGround.title) {
      await Taro.setNavigationBarTitle({ title: pageData.custom_backGround.title });
    }
    Taro.getSystemInfo({
      success: (res) => {
        this.setState({ systemInfo: res })
      }
    })
    const bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    const tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    vcmonitor(this)
    this.shareParams = await user.getSellerParams()
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
      const shareData = {
        title: platform.info.platformName,
        desc: platform.info.platformName,
        link: window.location.origin + '/common/custom/index?' + this.shareParams + '&customUuid=' + this.state.customUuid,
        imgUrl: platform.info.platformLogo
      }
      h5Wx.share(shareData)
    }
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, {temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds});
    }
    if (process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      this.setState({
        isUser: !identityIsSeller.isSeller
      })
    }
  }

  shareParams = ''
  page = 1

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: platform.info.platformName,
      path: '/common/custom/index?' + this.shareParams + '&customUuid=' + this.state.customUuid + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  onShareTimeline() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: platform.info.platformName,
      query: this.shareParams + '&customUuid=' + this.state.customUuid  + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore' && this.state.pageData.guessLike >= 0 && this.state.pageData.data_num == 1) {
      this.setState({loadMoreStatus: "loading"})
      const old = this.state.indexGoods
      const indexGoods = (await this.getIndexGoods(++this.page)) || []
      this.setState({indexGoods: [...old, ...indexGoods]})
    }
  }

  async getIndexGoods(page = 1) {
    const pageData = this.state.pageData;
    const indexGoods = await http.post<IndexGoods>(CUSTOM_GOODS, {
      p: page,
      customUuid: this.state.customUuid,
      areaId: this.props.location.region_id,
      dataLikeCustom: pageData.dataLikeCustom ? pageData.dataLikeCustom : '',
      sourceCustom: pageData.sourceCustom ? pageData.sourceCustom : ''
    })
    if (indexGoods) {
      if (indexGoods.list.length < 10) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return indexGoods.list
    } else {
      return []
    }
  }

  onPageScroll(page) {
    this.setState({scrollTop: page.scrollTop})
  }

  render() {
    const { pageData, showLoading, indexGoods, pageshowLoading, scrollTop, headTopAll, systemInfo, isUser, showLeftIcon, pageStyle, pageBgColor, pageBgImage, showSubTitle, showSearch } = this.state;
    const offSetTop = scrollTop > 100 ? 100 : scrollTop;
    const xAxis = 50 - offSetTop / 3.8;
    const top = headTopAll + 40 - offSetTop / 2.5;
    const maxWidth = systemInfo.screenWidth - 20;
    const width = maxWidth - (offSetTop + offSetTop * 0.2);
    return <View className='root customRoot' id='root' style={`background-color: ${!!pageStyle && pageBgColor};`}>
      {process.env.P_ENV === 'lx' && <View className='share-settings-components-logo share-settings-components-logo-big-bottom' onClick={() => Taro.navigateTo({ url: '/main/order/order' })}><Image mode='widthFix' className='share-settings-components-logo-img' src={RESOURCE_URL + '/resources/images/myorder.png'} /></View>}
      <GzhAuth />
      <Skeleton title className='paddingNone' loading={showLoading} titleWidth='100%' rowHeight='150px'>
        <Block>
          <View>
            {TARO_ENV !== 'h5' && TARO_ENV !== 'tt' && <View className='header-bar' style={`width: ${offSetTop > 80 ? 'inherit' : '100%'};`}><Headerbar showLeftIcon={showLeftIcon} opacity={offSetTop > 40 ? 0 : 1} title={pageData.custom_backGround.title} /></View>}
            <View className='head'>
              {showSearch && scrollTop >= 100 && <View className='search-bar' style={`opacity: ${scrollTop >= 100 ? 1 : 0};left: ${TARO_ENV === 'h5' ? '50' : xAxis}%;transform: translateX(-${TARO_ENV === 'h5' ? '50' : xAxis}%);width: ${TARO_ENV === 'h5' ? maxWidth : width}px;max-width: ${maxWidth}px;top: ${top}px;`}>
                {(scrollTop >= 100) && <CityLocation />}
              </View>}
            </View>
            <Image mode='widthFix' className='top-img' style={!pageStyle ? 'margin-bottom: 10px;' : ''} src={!!pageStyle ? pageBgImage : pageData.custom_backGround.img} />
            {showSearch && <View className='head-bg' style={`height:${headTopAll + 45}px;background: rgba(242,242,242,${Math.min(offSetTop / 100, 1)});`} />}
          </View>
        </Block>
      </Skeleton>
      <View className={`zoom ${!!pageStyle && 'customZoom'}`}>
        <Skeleton title loading={showLoading} titleWidth='100%' rowHeight='75px'>
          <Block>
            {pageData.custom_label && pageData.custom_label.length > 0 && <View style={!pageStyle ? 'background: inherit;' : ''} className={`categorys ${!!pageStyle && 'categorys-topic'}`}>
              <CustomMenu data={pageData.custom_label} />
            </View>}
          </Block>
        </Skeleton>
        <View className='custom_main' style={`background-color: ${!!pageStyle ? pageBgColor: ''} !important;`}>
          <Skeleton title loading={showLoading} row={1} rowHeight={280}>
            <Block>
              {!!pageStyle && pageData.custom_label && pageData.custom_label.length > 0 && !!pageData.hot_mudidi_custom && !!pageData.hot_mudidi_custom.length > 0 && <View style={`background-color: ${!!pageStyle && pageBgColor};height: 12px`} />}
              {!!pageData.hot_mudidi_custom && pageData.hot_mudidi_custom.map((item, index) => <View className={`hot ${index === 0 && 'first-hot'} ${index === pageData.hot_mudidi_custom.length - 1 && 'last-hot'}`} key={index}>
                <View className='title'>{item.custom_title ? item.custom_title : '热门目的地'}</View>
                <View className='content-box'>
                  {item.config_arr.length > 0 && item.config_arr.map(items => <View className='item' key={items.id} key={items.id} onClick={() => gotoPage(items.url)}>
                    <Image mode='aspectFill' src={items.img} className='img' />
                    <View className='name'>{items.name}</View>
                  </View>)}
                </View>
              </View>)}
            </Block>
          </Skeleton>
          {!!pageStyle && ((pageData.custom_label && pageData.custom_label.length > 0) || (pageData.hot_mudidi_custom && pageData.hot_mudidi_custom.length > 0)) && <View style={`background-color: ${pageBgColor};height: 12px`} />}
          <Skeleton loading={showLoading} title titleWidth='100%' rowHeight='150px'>
            <Block>
              {pageData.module.length > 0 && pageData.module.map((item, index) => <View className={`module-item ${index > 0 && 'module-item-m-t'} ${(item.type === 'limit3' || item.type === 'limit4' || item.type === 'advert') && 'no-bg'}`} key={index}>
                {item.type === 'limit1' && <View className='sale-module-1'>
                  <IndexSaleLimit1 isUser={isUser} {...item} />
                </View>}
                {item.type === 'limit2' && <View className='sale-module-2'>
                  <IndexSaleLimit2 isUser={isUser} {...item} />
                </View>}
                {item.type === 'limit3' && <View className='sale-module-3'>
                  <IndexSaleLimit3 {...item} />
                </View>}
                {item.type === 'limit4' && <View className='sale-module-3' style={!!pageStyle ? '' : 'margin: 0 10px;'}>
                  <IndexSaleLimit4 {...item} />
                </View>}
                {item.type === 'goods1' && <View className='most-module'>
                  <IndexSaleMost {...item} />
                </View>}
                {item.type === 'goods2' && <View className='most-module'>
                  <SwiperRecommend title={item.name} data={item.data} showMore={!!item.moreUrl} clickMore={() => {
                    Taro.navigateTo({url: item.moreUrl})
                  }}
                  />
                </View>}
                {item.type === 'goods3' && <View className='common-module'>
                  <IndexSaleCommon {...item} />
                </View>}
                {item.type === 'goods4' && <View className='common-module'>
                  <ShangxinToday isUser={isUser} showSubTitle={showSubTitle} data={item} />
                </View>}
                {item.type === 'goods5' && <View className='goods-box'>
                  {(item.name || item.moreUrl) && <View className='head_title'>
                    <View className='title'>{item.name}</View>
                    {!!item.moreUrl && <View className='right-more'>
                      <View onClick={() => gotoPage(item.moreUrl)}>
                        更多
                        <AtIcon value='chevron-right' size='16' color='#666' customStyle='line-height: inherit;' />
                      </View>
                    </View>}
                  </View>}
                  {!item.name && !item.moreUrl && <View style='height: 10px' />}
                  <View className='goods'><BigGoodsBox isUser={isUser} data={item.data} /></View>
                </View>}
                {item.type === 'goods6' && <View className='goods-box'>
                  {(item.name || item.moreUrl) && <View className='head_title'>
                    <View className='title'>{item.name}</View>
                    {!!item.moreUrl && <View className='right-more'>
                      <View onClick={() => gotoPage(item.moreUrl)}>
                        更多
                        <AtIcon value='chevron-right' size='16' color='#666' customStyle='line-height: inherit;' />
                      </View>
                    </View>}
                  </View>}
                  {!item.name && !item.moreUrl && <View style='height: 10px' />}
                  <View className='goods'><SmallGoodsBox data={item.data} /></View>
                </View>}
                {item.type === 'like1' && pageData.data_num == 0 && <View className='goods-box'>
                  <View className='head_title'><View className='title'>{pageData.guessLikeName || '猜你喜欢'}</View></View>
                  <View className='goods'><BigGoodsBox isUser={isUser} data={item.data} /></View>
                </View>}
                {item.type === 'like2' && pageData.data_num == 0 && <View className='goods-box'>
                  <View className='head_title'><View className='title'>{pageData.guessLikeName || '猜你喜欢'}</View></View>
                  <View className='goods'><SmallGoodsBox data={item.data} /></View>
                </View>}
                {item.type === 'advert' && <Image style='width: 100%;' onClick={() => gotoPage(item.moreUrl)} className='advert-img' src={item.advert_resource} mode='widthFix' />}
                {!pageStyle && index !== pageData.module.length - 1 && <View style='height: 10px;background-color: #f3f3f3;' />}
              </View>)}
            </Block>
          </Skeleton>
          <Skeleton title loading={pageshowLoading} row={3} rowHeight={220}>
            <Block>
              {!!pageStyle && (pageData.custom_label && pageData.custom_label.length > 0 || !!pageData.hot_mudidi_custom || pageData.module && pageData.module.length > 0) && <View style={`background-color: ${pageBgColor};height: 12px`} />}
              {pageData.guessLike >= 0 && pageData.data_num == 1 && <View className='goods-box module-item'>
                <View className='head_title'>
                  <View className='title'>{pageData.guessLikeName || '猜你喜欢'}</View>
                </View>
                <View className='goods'>
                  {pageData.guessLike === 1 && <SmallGoodsBox data={indexGoods} />}
                  {pageData.guessLike === 0 && <BigGoodsBox isUser={isUser} data={indexGoods} />}
                </View>
              </View>}
              {pageData.guessLike === -1 && <View className='iosx' />}
            </Block>
          </Skeleton>
        </View>
      </View>
    </View>;
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
